<template>
  <div class="wrapper">
    <div class="flex-1 h100 audit-box">
      <div class="header">
        <div class="title">文本检测</div>
        <div>
          <a-space>
            <a-button class="nbcs-btn nbcs-btn-search" @click="audit" v-if="permission('sys:checkTask:textData')">提交检测</a-button>
            <a-button class="nbcs-btn nbcs-btn-common" @click="allCorrect(true)" v-if="permission('sys:checkTask:yJJC')">一键纠错</a-button>
            <a-button class="nbcs-btn nbcs-btn-common" @click="allCorrect(false)" v-if="permission('sys:checkTask:yJHF')">一键恢复</a-button>
            <a-button class="nbcs-btn nbcs-btn-common" @click="clear" v-if="permission('sys:checkTask:clear')">清空</a-button>
            <!-- <a-button class="nbcs-btn nbcs-btn-common" @click="exportData" v-if="permission('sys:checkTask:textExport')">导出</a-button> -->
            <a-select style="width: 150px" v-model="searchForm.ruleId" placeholder="检测规则">
              <a-select-option :value="item.id" v-for="item in ruleList" :key="item.id">
                {{ item.ruleName }}
              </a-select-option>
            </a-select>
            <a-button class="nbcs-btn-main-bg" @click="exportData" v-if="permission('sys:checkTask:textExport')">下载检测报告</a-button>
          </a-space>
        </div>
      </div>
      <div class="_textarea" v-loading="loading">
        <my-tinymce ref="tinymce" id="_textarea" @input="input"></my-tinymce>
      </div>
      <div style="text-align: right; color: #999; font-size: 12px; margin-top: 4px">审核字数：{{ sum }}/10000</div>
    </div>
    <div class="result-box">
      <div class="header">
        <div class="title">检测建议</div>
        <!-- <div style="color: #333;font-size:12px">
          未通过：{{errList.length}}
        </div> -->
      </div>
      <div class="flex-1" style="overflow: auto; position: relative">
        <div class="margin-b-5" v-if="errList.length > 0">
          <span style="margin-bottom: 4px">错误等级：</span>
          <a-checkbox v-model="allError" @change="onCheckAllChange">全部</a-checkbox>
          <a-checkbox-group @change="onChange" v-model="checkedList" name="errorType" :options="errorList" />
        </div>
        <div class="margin-b-10" v-if="errList.length > 0">
          <div style="margin-bottom: 4px">违规类型</div>
          <div class="labelParent">
            <div class="active labelItem" @click="showLabel(0)">全部问题</div>
            <div
              class="labelItem"
              :class="firstLabelClassList[index]"
              @click="showLabel(index + 1, item, firstLabelClassList[index])"
              v-for="(item, index) in firstLabelList"
              :key="item"
            >
              {{ item }}
            </div>
          </div>
          <div class="labelChildren">
            <div :class="secondClass" v-for="item in secondLabelList" :key="item">{{ item }}</div>
          </div>
        </div>
        <template v-if="showErrList.length > 0">
          <text-result-card
            @assess="assess"
            :is-hf-show="permission('sys:checkTask:yJHF')"
            :is-update-show="permission('sys:checkTask:yJJC')"
            @correct="correct"
            @checkCard="adviceTagId => (checkCard = adviceTagId)"
            v-for="(item, index) in showErrList"
            :key="item.adviceTagId"
            :item="item"
            :wordId="item.keyWordLocationList[0].id"
            :index="index + 1"
            :checkCard="checkCard"
          ></text-result-card>
        </template>
        <no-data v-else-if="!init" tip="恭喜您!本次检测没有发现问题!"></no-data>
        <text-init v-else tip="暂无数据"></text-init>
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { textData, textExport } from '@/services/verify';
import MyTinymce from '@/components/MyTinymce';
import TextResultCard from './components/TextResultCard.vue';
// eslint-disable-next-line no-unused-vars
import { getPlainText, exportExcel, markWord, underlineWord } from '@/utils/util.js';
import { list } from '@/services/checkRule';
import NoData from '@/components/NoData';
import TextInit from '@/components/TextInit';
import { labelMap } from '@/utils/const.js';
export default {
  name: 'TextVerify',
  components: { MyTinymce, TextResultCard, NoData, TextInit },
  data() {
    return {
      init: true,
      text: '',
      loading: false,
      errList: [],
      errWordList: [],
      adviceWordList: [],
      ruleList: [],
      searchForm: {
        ruleId: ''
      },
      sum: 0,
      allError: true,
      errorList: [
        { label: '严重错误', value: '3' },
        { label: '错误', value: '1' },
        { label: '疑错', value: '2' }
      ],
      checkedList: ['1', '2', '3'],
      showErrList: [],
      textId: '',
      firstLabelList: [],
      firstLabelClassList: [],
      secondClass: '',
      secondLabelList: [],
      errorIdList: [],
      checkCard: '',
      labelMap
    };
  },
  computed: {},
  created() {
    this.getRule();
  },
  methods: {
    permission(name) {
      let permissions = this.$store.getters['account/permissions'];
      return permissions.filter(m => m.id == name || m.operation.indexOf(name) >= 0).length > 0;
    },
    showLabel(i, name, firstClass) {
      let labelItem = document.getElementsByClassName('labelItem');
      Array.prototype.forEach.call(labelItem, el => {
        el.classList.remove('active');
      });
      labelItem[i].classList.add('active');
      if (i == 0) {
        this.showErrList = this.errList.filter(item => this.checkedList.includes(item.level));
        this.secondLabelList = [];
        this.secondClass = '';
      } else {
        let tempErrList = this.errList.filter(item => this.checkedList.includes(item.level));
        this.showErrList = tempErrList.filter(item => item.firstLabelName == name);
        this.secondLabelList = this.showErrList.map(item => item.violateInfo);
        this.secondLabelList = [...new Set(this.secondLabelList)];
        this.secondClass = firstClass;
      }
    },
    audit() {
      this.init = false;
      if (this.$refs.tinymce.getTextContent().length > 10000) {
        this.$message.error('当前字数超出限制');
        return false;
      }
      this.loading = true;
      //过滤图片
      let title = getPlainText(this.text).substr(0, 10);
      // let first = this.text.split('</p>')[0];
      // let title = getPlainText(first.replace('<p>', '')).substr(0, 10);
      console.log(title);
      let content = getPlainText(this.text);
      if (content.trim() == '') {
        this.$message.warning('文本内容不能为空');
        this.loading = false;
        return false;
      }
      /////////////////////

      //////////////
      textData({
        text: '<body>' + this.text + '</body>',
        ruleId: this.searchForm.ruleId,
        title: title
      }).then(res => {
        console.log(res);
        this.loading = false;
        if (res.data.code == 0) {
          res.data.data.data.checkResultList = res.data.data.data.checkResultList.map(n => {
            n.taskId = res.data.data.data.id;
            n.isAuthAssess = 1;
            return n;
          });
          this.errList = res.data.data.data.checkResultList;
          this.textId = res.data.data.data.id;
          this.showErrList = this.errList.filter(item => this.checkedList.includes(item.level));
          this.showErrList.map(item => {
            item.tagClass = this.labelMap[item.firstLabelName];
          });
          this.firstLabelList = this.showErrList.map(item => item.firstLabelName);
          this.firstLabelList = [...new Set(this.firstLabelList)];
          this.firstLabelList.forEach(item => {
            this.firstLabelClassList.push(this.labelMap[item]);
          });
          // this.errWordList = this.errList.map(item => item.errWord);
          this.adviceWordList = this.errList.map(item => {
            if (item.corWord && item.corWord.length > 0) {
              return item.corWord[0];
            } else {
              return '';
            }
          });
          this.errWordList = []; //错词数组
          this.errorIdList = []; //错词id数组
          for (let i = 0; i < this.errList.length; i++) {
            this.errWordList.push(this.errList[i].errWord);
            //如果keyWordLocationList与错误词一对一则直接返回
            if (this.errList[i].keyWordLocationList.length == 1) {
              this.errorIdList.push(this.errList[i].keyWordLocationList[0].id);
            } else {
              //审核返回结果中可能出现keyWordLocationList为多个的bug处理
              let wordItem = this.errList[i].keyWordLocationList.find(item => item.keyWord == this.errList[i].errWord);
              if (wordItem) {
                this.errorIdList.push(wordItem.id);
              } else {
                this.errorIdList.push(this.errList[i].keyWordLocationList[0].id);
              }
            }
          }
          this.$refs.tinymce.setTextContent(res.data.data.data.content);
          this.$nextTick(() => {
            this.errorIdList.forEach((item, index) => {
              let word = document.getElementById('_textarea_ifr').contentWindow.document.getElementById(item);
              underlineWord(word, this.errList[index].firstLabelName);
            });
          });
        }
      });
    },
    allCorrect(flag) {
      this.errList.forEach((item, index) => {
        console.log(item);
        let el = document.getElementById('_textarea_ifr').contentWindow.document.getElementById(this.errorIdList[index]);
        if (el) {
          //修改
          if (flag) {
            el.innerText = item.corWord && item.corWord.length > 0 ? item.corWord[0] : '';
            el.style.border = 0;
          } else {
            //恢复
            el.innerText = item.errWord;
            underlineWord(el, item.firstLabelName);
          }
        }
      });
    },
    clear() {
      this.text = '';
      this.$refs.tinymce.setTextContent(this.text);
      this.sum = 0;
    },
    correct({ auditId, word, flag, firstLabelName }) {
      let el = document.getElementById('_textarea_ifr').contentWindow.document.getElementById(auditId);
      if (el) {
        //修改
        if (flag) {
          //为了取消锚点恢复对应颜色
          el.setAttribute('state', 1);
          el.style.border = 0;
        } else {
          //恢复
          el.setAttribute('state', 0);
          console.log(firstLabelName);
          underlineWord(el, firstLabelName);
        }
        el.innerText = word;
      }
      // this.$refs.tinymce.setTextContent(this.text);
      this.sum = this.$refs.tinymce.getTextContent().length;
    },
    exportData() {
      if (!this.textId) {
        this.$message.error('请先提交检测');
        return false;
      }
      this.loading = true;
      textExport({
        id: this.textId
      }).then(res => {
        this.loading = false;
        if (res.status == 200) {
          exportExcel(res.data, '检测报告.pdf', 'pdf');
        }
      });
    },
    input(value) {
      this.text = value;
      if (value.indexOf('<img ') > -1) {
        this.text = value.replace(/<img .*?>/g, '');
        this.$refs.tinymce.setTextContent(this.text);
      }
      this.sum = this.$refs.tinymce.getTextContent().length;
    },
    getRule() {
      list().then(res => {
        if (res.data.code === 0) {
          this.ruleList = res.data.data;
          this.searchForm.ruleId = this.ruleList[0].id;
        }
      });
    },
    onCheckAllChange() {
      if (this.allError) {
        this.checkedList = ['1', '2', '3'];
      } else {
        this.checkedList = [];
      }
      this.showErrList = this.errList.filter(item => this.checkedList.includes(item.level));
      this.firstLabelList = this.showErrList.map(item => item.firstLabelName);
      this.firstLabelList = [...new Set(this.firstLabelList)];
      this.firstLabelList.forEach(item => {
        this.firstLabelClassList.push(this.labelMap[item]);
      });
      this.showLabel(0);
    },
    onChange() {
      if (this.checkedList.length === this.errorList.length) {
        this.allError = true;
      } else {
        this.allError = false;
      }
      this.showErrList = this.errList.filter(item => this.checkedList.includes(item.level));
      this.firstLabelList = this.showErrList.map(item => item.firstLabelName);
      this.firstLabelList = [...new Set(this.firstLabelList)];
      this.firstLabelList.forEach(item => {
        this.firstLabelClassList.push(this.labelMap[item]);
      });
      this.showLabel(0);
    },
    assess(item, type) {
      let list = JSON.parse(JSON.stringify(this.showErrList));
      this.showErrList = [];
      this.showErrList = list.map(n => {
        if (n.uuid == item.uuid) n.result = type;
        return n;
      });
    }
  }
};
</script>

<style lang="less" scoped>
.wrapper {
  display: flex;
  background-color: #f4f9fd;
  .audit-box {
    background: #fff;
    border-radius: 6px;
    padding: 12px;
    display: flex;
    flex-direction: column;
    .header {
      width: 100%;
      // height: 34px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-left: 4px;
      margin-bottom: 12px;
      .title {
        color: #000;
        font-size: 16px;
        font-weight: bold;
        border-left: 4px solid #d43a3a;
        padding-left: 12px;
        // width: 90px;
      }
    }
    ._textarea {
      flex: 1;
      height: 100%;
      max-height: auto;
      font-size: 12px;
    }
  }
  .result-box {
    width: 530px;
    height: 100%;
    margin-left: 12px;
    background-color: #fff;
    border-radius: 6px;
    padding: 18px 12px;
    display: flex;
    flex-direction: column;
    .header {
      width: 100%;
      height: 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-left: 4px;
      margin-bottom: 12px;
      .title {
        color: #000;
        font-size: 16px;
        font-weight: bold;
        border-left: 4px solid #d43a3a;
        padding-left: 12px;
      }
    }
    .labelParent {
      display: flex;
      flex-wrap: wrap;
      & > div {
        border-radius: 4px;
        padding: 3px 6px;
        font-size: 13px;
        cursor: pointer;
        margin-right: 4px;
        margin-bottom: 4px;
        &:first-child {
          border: 1px solid #2b65f4;
          background-color: #f0f4f9;
          color: #2b65f4;
          &.active {
            background-color: #2b65f4;
            color: #fff;
            border: 1px solid #2b65f4;
          }
        }
      }
    }
    .labelChildren {
      display: flex;
      flex-wrap: wrap;
      margin-top: 6px;
      & > div {
        border-radius: 12px;
        padding: 3px 6px;
        font-size: 12px;
        margin-right: 4px;
        margin-bottom: 4px;
        &.cbz {
          border: 1px solid #46b1ff;
          color: #46b1ff;
        }
        &.ysxt {
          border: 1px solid #e05f5f;
          color: #e05f5f;
        }
        &.mgxx {
          border: 1px solid #ebc643;
          color: #ebc643;
        }
        &.scsh {
          border: 1px solid #17805a;
          color: #17805a;
        }
        &.flfg {
          border: 1px solid #36cdcd;
          color: #36cdcd;
        }
        &.grxx {
          border: 1px solid #fa906c;
          color: #fa906c;
        }
        &.kjmc {
          border: 1px solid #7a53e5;
          color: #7a53e5;
        }
        &.zdyc {
          border: 1px solid #78b45c;
          color: #78b45c;
        }
        &.qtmgxx {
          border: 1px solid #fa8701;
          color: #fa8701;
        }
      }
    }
    .cbz {
      &.active {
        background-color: #46b1ff;
        color: #fff;
        border: 1px solid #46b1ff;
      }
    }
    .ysxt {
      &.active {
        background-color: #e05f5f;
        color: #fff;
        border: 1px solid #e05f5f;
      }
    }
    .mgxx {
      &.active {
        background-color: #ebc643;
        color: #fff;
        border: 1px solid #ebc643;
      }
    }
    .scsh {
      &.active {
        background-color: #17805a;
        color: #fff;
        border: 1px solid #17805a;
      }
    }
    .flfg {
      &.active {
        background-color: #36cdcd;
        color: #fff;
        border: 1px solid #36cdcd;
      }
    }
    .grxx {
      &.active {
        background-color: #fa906c;
        color: #fff;
        border: 1px solid #fa906c;
      }
    }
    .kjmc {
      &.active {
        background-color: #7a53e5;
        color: #fff;
        border: 1px solid #7a53e5;
      }
    }
    .zdyc {
      margin-right: 0;
      &.active {
        background-color: #78b45c;
        color: #fff;
        border: 1px solid #78b45c;
      }
    }
    .qtmgxx {
      margin-right: 0;
      &.active {
        background-color: #fa8701;
        color: #fff;
        border: 1px solid #fa8701;
      }
    }
  }
}
</style>
